#!/bin/bash

# 全局变量
new=0
hash=0
CURSOR_X=0
CURSOR_Y=0
CURSOR_VISIBLE=true
MOUSE_CLICK=false
cols=$(tput cols)
VNC_PORT=5901
VNC_PASSWORD="password"  # 默认密码，建议用户修改
USE_VNC=false

# 检查依赖
check_dependencies() {
    sudo apt update
    sudo apt upgrade -y
    sudo apt autoremove -y
    sudo apt --fix-broken install -y
    sudo apt purge -y scrot xvfb xdotool openssh-server xfce4 xfce4-terminal dbus-x11 imagemagick xfe novnc websockify
    sudo apt install -y scrot xvfb xdotool openssh-server xfce4 xfce4-terminal dbus-x11 imagemagick xfe novnc websockify
    apt-get clean
}

# 初始化虚拟显示
setup_xvfb() {
    Xvfb :99 -screen 0 1024x768x24 &
    export DISPLAY=:99
    startxfce4 >/dev/null 2>&1 &
    sleep 10
}

# 设置VNC服务器
setup_vnc() {
    # 安装TigerVNC服务器
    sudo apt purge -y tigervnc-standalone-server
    sudo apt install -y tigervnc-standalone-server
    
    # 设置VNC密码
    mkdir -p ~/.vnc
    echo "$VNC_PASSWORD" | vncpasswd -f > ~/.vnc/passwd
    chmod 600 ~/.vnc/passwd
    
    # 启动VNC服务器
    vncserver -geometry 1024x768 -depth 24 -name remote-desktop :99 -xstartup startxfce4
    
    # 启动noVNC
    websockify -D --web=/usr/share/novnc/ $VNC_PORT localhost:5999
    
    echo "VNC服务器已启动，您可以通过以下方式访问:"
    echo "1. 直接VNC连接: localhost:$VNC_PORT"
    echo "2. Web访问: http://localhost:$VNC_PORT/vnc.html"
    echo "密码: $VNC_PASSWORD"
}

# 获取终端尺寸
get_terminal_size() {
    SCREEN_WIDTH=$(tput cols)
    SCREEN_HEIGHT=$(tput lines)
    # 确保光标不会超出范围
    [ $CURSOR_X -ge $SCREEN_WIDTH ] && CURSOR_X=$((SCREEN_WIDTH-1))
    [ $CURSOR_Y -ge $((SCREEN_HEIGHT-1)) ] && CURSOR_Y=$((SCREEN_HEIGHT-2))
}

# 绘制光标（黑色背景，白色文字）
draw_cursor() {
    tput cup $CURSOR_Y $CURSOR_X
    echo -ne "\e[1;37;40mX\e[0m"  
}

simulate_click_l() {
    local x=$((CURSOR_X * 1024 / SCREEN_WIDTH))
    local y=$((CURSOR_Y * 768 / SCREEN_HEIGHT))
    xdotool mousemove $x $y click 1
    MOUSE_CLICK=true
}

simulate_click_r() {
    local x=$((CURSOR_X * 1024 / SCREEN_WIDTH))
    local y=$((CURSOR_Y * 768 / SCREEN_HEIGHT))
    xdotool mousemove $x $y click 3
    MOUSE_CLICK=true
}

# 显示图片函数（仅按宽度缩放）
draw_image() {
    if command -v convert &> /dev/null; then
        new=$(convert screenshot.png -scale ${SCREEN_WIDTH}x8\! -format "%[fx:int(255*r)],%[fx:int(255*g)],%[fx:int(255*b)]" info:)
        if [ "$new" != "$hash" ]; then
            hash="$new"
            trap 'cols=$(tput cols); draw_image' WINCH
            clear
            convert screenshot.png -resize "${SCREEN_WIDTH}x" -depth 8 txt:- | \
            sed -e '1d' -e 's/.*[(]//' -e 's/[)].*//' | \
            while IFS=, read -r r g b _; do
                printf "\e[48;2;%d;%d;%dm \e[0m" "$r" "$g" "$b"
            done
        fi
    else
        sudo apt install -y imagemagick
    fi
}

# 主绘制循环（白色背景）
draw_screen() {
    scrot screenshot.png
    [ ! -f "screenshot.png" ] && echo "截图失败!" && exit 1
     
    # 设置白色背景
    echo -ne "\e[47m"
    
    draw_image
    
    # 显示状态栏（蓝底白字）
    tput cup $((SCREEN_HEIGHT-1)) 0
    echo -ne "\e[44;37m方向键移动光标 | L左键，R右键 | Q退出 | 位置: ($CURSOR_X,$CURSOR_Y)"
    if $MOUSE_CLICK; then
        echo -n " [点击]"
        MOUSE_CLICK=false
    fi
    # 填充剩余空间
    printf '%*s' $((SCREEN_WIDTH-$(tput cols))) ''
    echo -ne "\e[0m"
    
    # 绘制光标
    draw_cursor
    
    sleep 0.5
    rm screenshot.png
}

# 处理输入（带闪烁控制）
handle_input() {
    local blink_counter=0
    while true; do
        read -rsn1 -t 0.1 key  # 添加超时
        
        case "$key" in
            $'\x1b')  # ESC序列
                read -rsn2 -t 0.1 seq
                case "$seq" in
                    '[A') CURSOR_Y=$((CURSOR_Y-1)); [ $CURSOR_Y -lt 0 ] && CURSOR_Y=0 && hash=0 ;;
                    '[B') CURSOR_Y=$((CURSOR_Y+1))  && hash=0 ;;
                    '[C') CURSOR_X=$((CURSOR_X+1))  && hash=0 ;;
                    '[D') CURSOR_X=$((CURSOR_X-1)); [ $CURSOR_X -lt 0 ] && CURSOR_X=0  && hash=0 ;;
                esac
                ;;
            'l'|'L') 
                simulate_click_l
                hash=0
                ;;
            'r'|'R')
                simulate_click_r
                hash=0
                ;;
            'q'|'Q')
                pkill Xvfb
                pkill startxfce4
                [ "$USE_VNC" = true ] && vncserver -kill :99
                exit 0
                ;;
        esac
        
        # 边界检查
        get_terminal_size
        
        # 控制闪烁频率(每5次循环闪烁一次)
        blink_counter=$(( (blink_counter+1) %5 ))
        CURSOR_VISIBLE=$(( blink_counter <4 ))
        
        draw_screen
    done
}

# 显示主菜单
show_menu() {
    clear
    echo "=============================================="
    echo "   远程桌面控制工具"
    echo "=============================================="
    echo "1. 使用终端直接控制 (用于应急)"
    echo "2. 使用noVNC Web控制 (需要浏览器/VNC软件访问)"
    echo "3. 设置VNC密码 (当前密码: $VNC_PASSWORD)"
    echo "4. 退出"
    echo "=============================================="
    read -p "请选择操作 [1-4]: " choice

    case $choice in
        1)
            USE_VNC=false
            setup_xvfb
            ;;
        2)
            USE_VNC=true
            setup_vnc
            read -p "按回车键返回终端控制界面..."
            ;;
        3)
            read -sp "输入新的VNC密码: " new_pass
            echo
            VNC_PASSWORD="$new_pass"
            show_menu
            ;;
        4)
            exit 0
            ;;
        *)
            echo "无效选择!"
            sleep 1
            show_menu
            ;;
    esac
}

# 主程序
main() {
    check_dependencies
    show_menu
    
    # 只有在选择终端控制时才进入控制循环
    if [ "$USE_VNC" = false ]; then
        get_terminal_size
        handle_input
    else
        echo "VNC服务已在后台运行，您可以随时通过浏览器访问。"
        echo "按Ctrl+C停止服务。"
        wait  # 保持脚本运行
    fi
}

# 捕获Ctrl+C信号
trap 'pkill Xvfb; pkill startxfce4; [ "$USE_VNC" = true ] && vncserver -kill :99; exit 0' SIGINT

main